<?php

/*
 * Bdata第一步：封装初始化基础配置信息类
 * 当$isCache=1（即需要缓存时），需要判断基础数据是否更新
 */

namespace Common\Controller;

/**
 * Description of BdataConfigController
 *
 * @author chenghui
 */
class BdataConfigController {
    private $isCache;//是否使用缓存，1为使用，0为不使用
    private $code;//分析代号：对应不同的分析模型
    private $dirName;//缓存路径

    /**
     * @构造：
     * @param type $code
     * @param type $isCache
     */
    public function __construct($code,$isCache){
        $this->code = empty($code)?'Bdata':$code;
        $this->isCache = empty($isCache)?0:$isCache;
        $this->dirName = 'Bdata';
    }    
    
    
    public function setUpdateMark(){
        
    }

    /**
     * @缓存维度基础配置信息:用于解析维度
     * @param type $code 代号
     * @return type 配置数组
     */
    public function getAxisConfig(){
        if($this->isCache>0){
            $file=$this->dirName.'/'.$this->code.'/'.'AxisConfig';
            $AxisConfig=F($file);
            
            if(empty($AxisConfig)){
                $AxisConfig = $this->fetchAxisConfig();
                
                F($file,$AxisConfig);
            }
        }else{
            $AxisConfig = $this->fetchAxisConfig();
        }        
        return $AxisConfig;
    }
    
    /**
     * @读取配置表中的对照信息：用于读取中文涵义
     * @param type $code
     * @return type
     */
    public function getContrastConfig(){
        if($this->isCache>0){
            $file=$this->dirName.'/'.$this->code.'/'.'ContrastConfig';
            $ContrastConfig=F($file);
            
            if(empty($ContrastConfig)){
                $ContrastConfig = $this->fetchContrastConfig();
                
                F($file,$ContrastConfig);
            }
        }else{
            $ContrastConfig = $this->fetchContrastConfig();
        }        
        return $ContrastConfig;
    }
    
    /**
     * @读取配置表中数据精度信息
     * @param type $code
     * @return type
     */
    public function getAccuracyConfig(){
        if($this->isCache>0){
            $file=$this->dirName.'/'.$this->code.'/'.'AccuracyConfig';
            $AccuracyConfig=F($file);
            if(empty($AccuracyConfig)){
                $AccuracyConfig = $this->fetchAccuracyConfig();
                F($file,$AccuracyConfig);
            }
        }else{
            $AccuracyConfig = $this->fetchAccuracyConfig();
        }
        return $AccuracyConfig;
    }
        
    /**
     * @获取可作为条件的字段表达式
     * @param type $code
     * @return type
     */
    public function getCoditionConfig(){
        if($this->isCache>0){
            $file=$this->dirName.'/'.$this->code.'/'.'CoditionConfig';
            $CoditionConfig=F($file);
            if(empty($CoditionConfig)){
                $CoditionConfig = $this->fetchCoditionConfig();
                F($file,$CoditionConfig);
            }
        }else{
            $CoditionConfig = $this->fetchCoditionConfig();
        }
        
        return $CoditionConfig;
    }
    
    
    /**
     * @获取可作为分析维度的字段表达式
     * @param type $code
     * @return type
     */
    public function getAxisConfigDetail(){
        if($this->isCache>0){
            $file=$this->dirName.'/'.$this->code.'/'.'AxisConfigDetail';
            $AxisConfigDetail=F($file);
            if(empty($AxisConfigDetail)){
                $AxisConfigDetail = $this->fetchAxisConfigDetail();
                F($file,$AxisConfigDetail);
            }
        }else{
            $AxisConfigDetail = $this->fetchAxisConfigDetail();
        }
        
        return $AxisConfigDetail;
    }
    
    
    /**
     * @获取可作为统计维度的字段表达式
     * @param type $code
     * @return type
     */
    public function getCountAxisConfig(){
        if($this->isCache>0){
            $file=$this->dirName.'/'.$this->code.'/'.'CountAxisConfig';
            $CountAxisConfig=F($file);
            if(empty($CountAxisConfig)){
                $CountAxisConfig = $this->fetchCountAxisConfig();
                F($file,$CountAxisConfig);
            }
        }else{
            $CountAxisConfig = $this->fetchCountAxisConfig();
        }
        
        return $CountAxisConfig;
    }
    
    
    /**
     * @获得数据源表达式
     * @param type $code
     * @return type
     */
    public function getDataBaseConfig(){
        if($this->isCache>0){
            $file=$this->dirName.'/'.$this->code.'/'.'BaseConfig';
            $BdataBaseConfig=F($file);
            if(empty($BdataBaseConfig)){
                $BdataBaseConfig=$this->fetchBaseConfig();
                F($file,$BdataBaseConfig);
            }
        }else{
            $BdataBaseConfig=$this->fetchBaseConfig();
        }
        
        return $BdataBaseConfig;
    }    
    
    
    /**
     * @获得特殊计算的表达式
     * @param type $code
     * @return type
     */
    public function getBdataSpecial(){
        if($this->isCache>0){
            $file=$this->dirName.'/'.$this->code.'/'.'BdataSpecial';
            $BdataSpecial=F($file);
            if(empty($BdataSpecial)){
                $BdataSpecial=$this->fetchBdataSpecial();
            }
        }else{
            $BdataSpecial=$this->fetchBdataSpecial();
        }
        
        return $BdataSpecial;
    }
    
    
    /**
     * @方法：分析统计数据的计量单位
     * @param type $code
     * @return type
     */
    public function getUomConfig(){
        if($this->isCache>0){
            $file=$this->dirName.'/'.'UomConfig';
            $UomConfig=F($file);
            
            if(empty($UomConfig)){
                $UomConfig=$this->fetchUomConfig();
                F($file,$UomConfig);
            }
        }else{
            $UomConfig=$this->fetchUomConfig();
        }
        return $UomConfig;
    }
    
    /**
     * @方法：获取统计方法数组
     * @param type $code
     * @return type
     */  
    public function getCountConfig(){
        if($this->isCache>0){
            $file=$this->dirName.'/'.'CountConfig';
            $CountConfig=F($file);
            
            if(empty($CountConfig)){
                $CountConfig=$this->fetchCountConfig();
                F($file,$CountConfig);
            }
        }else{
            $CountConfig=$this->fetchCountConfig();
        }     
        return $CountConfig;
    }
    
    /**
     * @动态执行数据更新
     * @param type $code
     * @return type
     */
    public function getBdataImport_log(){
        $file=$this->dirName.'/'.'BdataImportLog';
        $BdataImportLog = F($file);
        if($this->isCache>0 && empty($BdataImportLog)){
             $sql='select dataType,num,idMin,idMax,LastDate,date from '.C('DB_PREFIX').'bdata_import_log where [id] in (select max(id) from '.C('DB_PREFIX').'bdata_import_log where status=1 group by datatype)';
			 
                $data = M()->query($sql);
                foreach ($data as $val){
                    $key=$val['dataType'];
                    $array['num']=$val['num'];
                    $array['idMin']=$val['idMin'];
                    $array['idMax']=$val['idMax'];
                    $array['LastDate']=$val['LastDate'];
                    $array['date']=$val['date'];
                    $BdataImportLog[$key]=$array;
                }
                F($file,$BdataImportLog); 
        }

        return $BdataImportLog;
    }
    
    
    /**
     * @方法：解析所有条件时数据：支持缓存
     * @return type
     */
    public function getConditionsData($defaultConditon){
        $data=$this->fetchConfigDetail($defaultConditon);
      
        if($this->isCache==1){//需要缓存时
            foreach($data as $var){
                $key = strtoupper($var['FieldColumn']);
                if($var['FieldType']==1){//对照时
                    $file=$this->dirName.'/'.$this->code.'/'.$key;
                    $where = F($file);
                    if(empty($where)){
                        $where['FieldColumn'] = $key;
                        $where['FieldName'] = $var['FieldName'];
                        $where['FieldType'] = $var['FieldType'];
                        $where['UomName'] = $var['UomName'];
                        $where['button'] = $var['button'];    
                        $where['item']=$this->fetchDataDetail($var);
                        $whereData[$key] = $where;
                        F($file,$where);
                    }else{
                        $whereData[$key] = $where;
                    }
                }else{//其他类型
                    $where['FieldColumn'] = $key;
                    $where['FieldName'] = $var['FieldName'];
                    $where['FieldType'] = $var['FieldType'];
                    $where['UomName'] = $var['UomName'];
                    $where['button'] = $var['button'];
                    $whereData[$key] = $where;
                }
            }
        }else{//不需要缓存
            $whereData=$this->parseConfigNoCatchData($data);
        }
        
        return $whereData;
    }
    
    /**
     * @获取所有条件数组
     * @return type
     */
    public function fetchAllConditions(){

        if($this->isCache==1){//需要缓存时
            $file=$this->dirName.'/'.$this->code.'/'.'AllConditions';
            $whereData = F($file);
            if(empty($whereData)){
                $data=$this->fetchAllConditionConfig();
                foreach($data as $var){
                    $key = strtoupper($var['FieldColumn']);
                    if($var['FieldType']==1){//对照时
                        $where['FieldColumn'] = $key;
                        $where['FieldName'] = $var['FieldName'];
                        $where['FieldType'] = $var['FieldType'];
                        $where['UomName'] = $var['UomName'];
                        $where['button'] = $var['button'];    
                        $where['item']=$this->fetchDataDetail($var);
                        $whereData[$key] = $where;
                    }else{
                        $where['FieldColumn'] = $key;
                        $where['FieldName'] = $var['FieldName'];
                        $where['FieldType'] = $var['FieldType'];
                        $where['UomName'] = $var['UomName'];
                        $where['button'] = $var['button'];
                        $whereData[$key] = $where;
                    }
                }
                F($file,$whereData);
            }
        }else{
            $whereData=$this->parseConfigNoCatchData($data);
        }
        
        return $whereData;
    }
    
    
    /**
     * @更新分析数据
     */
    public function updateDataTempTable(){
        M()->prepare('updateTempStockAnalyze');
        $file=$this->dirName.'/'.'BdataImportLog';
        F($file,NULL);
    } 
    
    /**
     * @读取配置表数据
     * @return type
     */
    private function fetchAxisConfig(){
        $AxisConfig = array();
        $sql="select FieldColumn,FieldName,FieldType,DataColumn,Expression,IsAxis,IsCount,Uom,isnull(b.title,'') as UomName,IsNull "
              . " from ".C('DB_PREFIX')."Configure as a"
              . " left join ".C('DB_PREFIX').'uom'.' as b on b.id=a.uom '
              . "where Code='".$this->code."'";
        $dataArr=  M()->query($sql);
        
        foreach($dataArr as $val){
            $arr=array();
            $key=  strtoupper($val['FieldColumn']);
            $arr['FieldName']=$val['FieldName'];
            $arr['FieldType']=$val['FieldType'];
            $arr['DataColumn']=$val['DataColumn'];
            $arr['Expression']=$val['Expression'];
            $arr['IsAxis']=$val['IsAxis'];
            $arr['IsCount']=$val['IsCount'];
            $arr['Uom']=$val['Uom'];
            $arr['UomName']=$val['UomName'];
            $arr['IsNull']=$val['IsNull'];
            
            $AxisConfig[$key]=$arr;
        }
        //追加虚拟维度的配置信息
        $AxisConfig['rank']=array('FieldName'=>'排名');
        $AxisConfig['yAxis']=array('FieldName'=>'统计');
        $AxisConfig['sums']=array('FieldName'=>'合计');
        
        return $AxisConfig;
    }
    
    /**
     * @读取配置表中对照表信息
     * @return type
     */
    private function fetchContrastConfig(){
        $ContrastConfig = array();
        $sql="select FieldColumn,FieldType,ContrastSheet,ContrastId,ContrastName,ContrastSort "
              . " from ".C('DB_PREFIX')."Configure "
              . " where Code='".$this->code."'";
        $dataArr=  M()->query($sql);

        foreach($dataArr as $val){
            $arr=array();
            $key=  strtoupper($val['FieldColumn']);

            $arr['ContrastSheet']=$val['ContrastSheet'];
            $arr['FieldType']=$val['FieldType'];
            $arr['ContrastId']=$val['ContrastId'];
            $arr['ContrastName']=$val['ContrastName'];
            $arr['ContrastSort']=$val['ContrastSort'];  

            $ContrastConfig[$key]=$arr;
        }
        return $ContrastConfig;
    }
    
    /**
     * @获取配置表中的数字型字段的精度
     * @return type
     */
    private function fetchAccuracyConfig(){
        $AccuracyConfig = array();
        $sql="select FieldColumn,isnull(Accuracy,0) as Accuracy "
              . " from ".C('DB_PREFIX')."Configure "
              . " where Code='".$this->code."' and FieldType=3";
        
        $dataArr=  M()->query($sql);

        foreach($dataArr as $val){
            $key = strtoupper($val['FieldColumn']);
            $AccuracyConfig[$key]=$val['Accuracy'];
        }
        return $AccuracyConfig;
    }
    
    /**
     * 
     * @return type
     */
    private function fetchCoditionConfig(){
        $CoditionConfig = array();
        $sql="select FieldColumn,CountRules,Uom,DefaultValue "
              . " from ".C('DB_PREFIX')."Configure "
              . " where Code='".$this->code."'".' and IsWhere > 0 '
              .' order by Sort';
        $dataArr=  M()->query($sql);

        foreach($dataArr as $val){
            $arr=array();
            $key=  strtoupper($val['FieldColumn']);

            if(!empty($val['CountRules'])){
                $arr['CountRules']=$val['CountRules'];
                $arr['Uom']=$val['Uom'];
                $arr['DefaultValue']=$val['DefaultValue'];

                $CoditionConfig[$key]=$arr;
            }
        }
        return $CoditionConfig;
    }
    
    /**
     * @解析维度配置明细
     * @return type
     */
    private function fetchAxisConfigDetail(){
	
        $sql="select FieldColumn,FieldName,CountRules,UomGroup,Uom,DefaultValue as rules,FieldType,Sort,isAxis "
              . " from ".C('DB_PREFIX')."Configure "
              . " where Code='".$this->code."'".' and isAxis > 0 '
              .' order by Sort';
        $dataArr=  M()->query($sql);
        return $dataArr;
    }
    
    /**
     * @解析统计维度配置明细
     * @return type
     */
    private function fetchCountAxisConfig(){
        $sql="select FieldColumn,FieldName,CountRules,UomGroup,Uom,DefaultValue,FieldType,Sort "
              . " from ".C('DB_PREFIX')."Configure "
              . " where Code='".$this->code."'".' and isCount > 0 '
              .' order by Sort';
        $dataArr=  M()->query($sql);
        return $dataArr;
    }
        /**
     * @读取基础数据库配置表
     * @return type
     */
    private function fetchBaseConfig(){
        $BdataBaseConfig = array();
        $sql="select Code,DataType,DataExp,Param,DigTable "
              . " from ".C('DB_PREFIX')."BdataBase "
              ." where code='".$this->code."'";
        $dataArr=  M()->query($sql);

        foreach($dataArr as $val){
            $BdataBaseConfig['Code']=$val['Code'];
            $BdataBaseConfig['DataType']=$val['DataType'];
            $BdataBaseConfig['DataExp']=$val['DataExp'];
            $BdataBaseConfig['Param']=$val['Param'];
            $BdataBaseConfig['DigTable']=$val['DigTable'];
        }
        return $BdataBaseConfig;
    }
    
    /**
     * @读取特殊计算配置信息
     * @return type
     */
    private function fetchBdataSpecial(){
        $BdataSpecial = array();
        $sql="select Id,FieldCode,FieldColumn,FieldExp,FieldValue,FieldOut "
              . " from ".C('DB_PREFIX')."BdataSpecial "
              . " where Code='".$this->code."'";
        $dataArr=  M()->query($sql);

        foreach($dataArr as $val){
            $key=$val['Id'];
            $BS['FieldCode']=  strtoupper($val['FieldCode']);
            $BS['FieldColumn']=$val['FieldColumn'];
            $BS['FieldExp']=$val['FieldExp'];
            $BS['FieldValue']=$val['FieldValue'];
            $BS['FieldOut']=$val['FieldOut'];
            $BdataSpecial[$key]=$BS;
        }
        return $BdataSpecial;
    }
    
    /**
     * @读取单位配置信息
     * @return type
     */
    private function fetchUomConfig(){
        $UomConfig=array();
        $sql='select a.id as UomId,b.id as UomGroupId,a.title as UomName,IsMain,Rate '
             .' from '.C('DB_PREFIX')."uom".' as a '
             .' inner join '.C('DB_PREFIX')."uomgroup ".' as b on b.id=a.uomgroup ';
        $dataArr=M()->query($sql);

        foreach($dataArr as $val){
            $arr=array();
            $key=strtoupper($val['UomId']);

            $arr['UomGroupId']=$val['UomGroupId'];
            $arr['UomName']=$val['UomName'];
            $arr['IsMain']=$val['IsMain'];
            $arr['Rate']=ceil($val['Rate']);

            $UomConfig[$key]=$arr;
        }
        return $UomConfig;
    }
    
    /**
     * @获取统计规则信息
     * @return type
     */
    private function fetchCountConfig(){
        $CountConfig=array();
        $sql='select Id,Code,Title from '.C('DB_PREFIX').'count';
        $dataArr=M()->query($sql);

        foreach($dataArr as $val){
            $arr=array();
            $key=strtoupper($val['Code']);
            $arr['Id']=$val['Id'];
            $arr['CountName']=$val['Title'];

            $CountConfig[$key]=$arr;
        }
        return $CountConfig;
    }
    

    /**
     * @获取配置表明细
     * @param type $var
     * @return type
     */
    private function fetchConfigDetail($defaultConditon){
        if(!empty($defaultConditon)){
            $con = array();
            foreach ($defaultConditon as $key){
                $con[]="'".$key."'";
            }
            $wCon = implode(',', $con);
            $conWhere = empty($wCon)?'':" and FieldColumn in(".$wCon.")";
        }else{
            $conWhere='';
        }

        $sql="select FieldColumn,FieldName,FieldType,b.title as UomName,button,ContrastSheet as cSheet,ContrastId as cId,ContrastName as cName,ContrastSort as cSort,ContrastWhere as cWhere,ContrastIsUpdate as IsUpdate "
                ." from ".C('DB_PREFIX')."Configure as a "
                ." left join ".C('DB_PREFIX')."uom as b on a.Uom=b.id "
                ." where code='".$this->code."' and iswhere = 1 ".$conWhere.' order by sort';

        $data=M()->query($sql);
        return $data;
    }
    
    /**
     * @获取配置表明细
     * @param type $var
     * @return type
     */
    private function fetchAllConditionConfig(){

        $sql="select FieldColumn,FieldName,FieldType,b.title as UomName,button,ContrastSheet as cSheet,ContrastId as cId,ContrastName as cName,ContrastSort as cSort,ContrastWhere as cWhere,ContrastIsUpdate as IsUpdate "
                ." from ".C('DB_PREFIX')."Configure as a "
                ." left join ".C('DB_PREFIX')."uom as b on a.Uom=b.id "
                ." where code='".$this->code."' and iswhere = 1 ".' order by sort';
        
        $data=M()->query($sql);
        return $data;
    }
    
    /**
     * @获得条件明细
     */
    public function getConditionColumn(){
        $data = $this->fetchAllConditionConfig();
        $result = array();
        foreach ($data as $val){
            $result[] = array('name'=>$val['FieldColumn'],'title'=>$val['FieldName']);
        }
        return $result;
    }

    /**
     * 解析配置表数据:条件项
     * @param type $data
     * @return type
     */
    private function parseConfigNoCatchData($data){
        foreach($data as $var){
            $key = strtoupper($var['FieldColumn']);
            $whereData[$key]['FieldColumn'] = $key;
            $whereData[$key]['FieldName'] = $var['FieldName'];
            $whereData[$key]['FieldType'] = $var['FieldType'];
            $whereData[$key]['UomName'] = $var['UomName'];
            $whereData[$key]['button'] = $var['button'];
            if($var['FieldType']==1){
                $whereData[$key]['item']=$this->fetchDataDetail($var);
            }            
        }
        return $whereData;
    }
    
    /**
     * 解析配置表数据:条件项
     * @param type $data
     * @return type
     */
    private function parseNoCatchData($var){
        if($var['IsUpdate']==1){//有更新
            $where['FieldColumn'] = $key;
            $where['FieldName'] = $var['FieldName'];
            $where['FieldType'] = $var['FieldType'];
            $where['UomName'] = $var['UomName'];
            $where['button'] = $var['button'];    
            $where['item']=$this->fetchDataDetail($var);
            $whereData[$key] = $where;
            if($var['FieldType']==1){
                F($file,$where);
            }            
        }else{
            $where = F($file);
            if(empty($where)){
                $where['FieldColumn'] = $key;
                $where['FieldName'] = $var['FieldName'];
                $where['FieldType'] = $var['FieldType'];
                $where['UomName'] = $var['UomName'];
                $where['button'] = $var['button'];    
                $where['item']=$this->fetchDataDetail($var);
                $whereData[$key] = $where;
                if($var['FieldType']==1){
                    F($file,$where);
                }
            }else{
                $whereData[$key] = $where;
            }                    
        }
        return $whereData;
    }

    /**
     * @方法：根据配置表读取基础数据表明细
     * @param type $var
     * @return type
     */
    private function fetchDataDetail($var){
        $where = empty($var['cWhere'])?'':' where '.$var['cWhere'];
        
        $sql='select '.$var['cId'].' as id,'.$var['cName'].' as title from '.$var['cSheet'].$where.' order by '.$var['cSort'];
        $Data=M()->query($sql);
        return $Data;
    }
    
    public function test(){
        $stime=microtime(true); 
//        $sql = "select yy,mt_company.title+'@'+mt_project.title+'@'+mt_formats.title as yAxis,jzmj from (
//                select yy,lpmc,kfs,yt,sum(jzmj) as jzmj from (select year(cjrq) as yy,lpmc,kfs,yt,jzmj from mt_AnalyTable) as t group by yy,kfs,lpmc,yt
//                ) as tt
//                inner join mt_project on mt_project.id=tt.lpmc
//				inner join mt_company on mt_company.id=tt.kfs
//				inner join mt_formats on mt_formats.id=tt.yt
//                order by yy,lpmc,kfs,yt";
        
        $sql = "select yy,mt_housetype.title as yAxis,jzmj from (
                select yy,hx,sum(jzmj) as jzmj from (select year(cjrq) as yy,hx,jzmj from mt_AnalyTable) as t group by yy,hx
                ) as tt 
		inner join mt_housetype on mt_housetype.id=tt.hx 
                order by yy,hx";
        $data = M()->query($sql);
        
        $yy = array_column_result($data,'yAxis');
        $year = array_unique($yy);
        echo count($year);echo '<br>';
var_dump($year);exit();
        printf(' memory usage: %01.2f MB', memory_get_usage()/1024/1024);
        //var_dump($year);echo '<br>';
        $etime=microtime(true); 
        echo '取数：';echo $etime-$stime;echo '<br>';
        
        foreach ($data as $val){
            $rrs[$val['yy']][$val['yAxis']]=$val['jzmj'];
        }
        $ktime=microtime(true); 
        printf(' memory usage: %01.2f MB', memory_get_usage()/1024/1024);
        echo '行转列：';echo $ktime-$etime;echo '<br>';
        var_dump($rrs);
        
        foreach ($year as $val){
            $str = explode('@', $val);
            
            $res[0][]=$str[0];
            $res[1][]=$str[1];
            $res[2][]=$str[2];
            $res[3][]=$str[3];
        }
        $dtime=microtime(true); 
        printf(' memory usage: %01.2f MB', memory_get_usage()/1024/1024);
        echo '解析表头：';echo $dtime-$ktime;echo '<br>';
        foreach ($res as $val){
           $result[] = array_count_values($val);
        }
        
        $gtime=microtime(true); 
        echo $gtime-$dtime;echo '<br>';
        
        //var_dump($result);
        exit();
    }
    
}
